package com.jzo2o.orders.manager.listener;

import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.JsonUtils;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-04-03 10:18
 */
@Component
@Slf4j
public class TradeStatusListener {
    @Resource
    private IOrdersCreateService ordersCreateService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, durable = "true"),
                    exchange = @Exchange(value = MqConstants.Exchanges.TRADE, type = "topic", durable = "true"),
                    key = {MqConstants.RoutingKeys.TRADE_UPDATE_STATUS}
            )
    )
    public void listenerPayNotifyMessage(String message) {
        log.info("收到支付通知消息：{}", message);
        if (StringUtils.isNotBlank(message)) {
            // 1. 解析消息
            List<TradeStatusMsg> tradeStatusMsgs = JsonUtils.toList(message, TradeStatusMsg.class);
            if(CollUtils.isNotEmpty(tradeStatusMsgs)){
                // 2. 遍历消息
                tradeStatusMsgs.forEach(tradeStatusMsg -> {
                    // 3. 判断消息是否属于jzo2o业务，并且交易单支付状态为“已结算”
                    if("jzo2o-orders".equals(tradeStatusMsg.getProductAppId()) && TradingStateEnum.YJS.getCode().equals(tradeStatusMsg.getStatusCode())){
                        // 4. 更新订单信息
                        ordersCreateService.paySuccess(tradeStatusMsg);
                    }
                });
            }

        }
    }
}
